
$(document).ready( 
	function()
	{
	
		$("#content").removeAttr('disabled');
		$("#serviceblock").mouseout( MouseOutEvent );
		$("#serviceblock > div").mouseenter( MouseEnterEvent ).click( SelectScoreEvent );
		$("#realityblock").mouseout( MouseOutEvent );
		$("#realityblock > div").mouseenter( MouseEnterEvent ).click( SelectScoreEvent );
		$("#velocityblock").mouseout( MouseOutEvent );
		$("#velocityblock > div").mouseenter( MouseEnterEvent ).click( SelectScoreEvent );
		$("#rateblock").mouseout( MouseOutEvent );
		$("#rateblock > div").mouseenter( MouseEnterEvent ).click( SelectScoreEvent );
		$("#scoreblock").mouseout( MouseOutEvent );
		$("#scoreblock > div").mouseenter( MouseEnterEvent ).click( SelectScoreEvent );
		$("a").css( "cursor", "pointer" );

		if( $("#action").val() == "modify_review" ){
			LoadScore( $("#serviceblock"), $("#service").val() );
			LoadScore( $("#realityblock"), $("#reality").val()  );
			LoadScore( $("#velocityblock"), $("#velocity").val()  );
			LoadScore( $("#rateblock"), $("#rate").val()  );
			LoadScore( $("#scoreblock"), $("#score").val()  );

			SetCheckBoxList( "paymethod", $('#paymethod_list').val() );
			SetCheckBoxList( "feature", $('#feature_list').val() );
		}
		else
		{
			LoadScore( $("#serviceblock"), 0 );
			LoadScore( $("#realityblock"), 0 );
			LoadScore( $("#velocityblock"), 0 );
			LoadScore( $("#rateblock"), 0 );
			LoadScore( $("#scoreblock"), 0 );
		}
	
		
		if( typeof(add_review) != 'undefined' && add_review == 1 ) {
			$("#content").css('color', 'gray');
			$("#content").focus(function(){
				if( firstFocus == 0 ){
					$(this).val('');
					$(this).css('color', 'black' );
					firstFocus = 1;
				}
			});

		}
		
		$("#submitReview").css( 'visibility', 'visible');
		
		$("#apTip").mouseenter(AddProductTipEnterEvent )
		$("#apTip").mouseout( AddProductTipOutEvent );

                $("#vbox").hide();
   
                $("#vcode").click(function(){

                refresh_vcode( edp_domain_url + 'vcode');
                $("#vbox").show();

   });
	}
);
    

function refresh_vcode(url){

   $("#vimg").attr('src',url);

}

var firstFocus = 0;

function AfterPublishWithoutError()
{
        ClearAfterDone();
	location.href = location.href;
}

function ClearAfterDone()
{
	LoadScore( $("#serviceblock"), 0 );
	LoadScore( $("#realityblock"), 0 );
	LoadScore( $("#velocityblock"), 0 );
	LoadScore( $("#rateblock"), 0 );
	LoadScore( $("#scoreblock"), 0 );
	$("div[id=ratingResult]").html('');//add by bo @0720
	$("#content").val("");
	$("#tag").val("");
	
	$("input[tag=paymethod]").attr("checked", '');
	$("input[tag=feature]").attr("checked", '');
	
	$(".tags a").css( "background", "" );
	$("#product_lists").val("");
	$("#product_list").html('');
	$("#files").val("");
	$("#picnames").val("");
	$(".fileblock").remove();
	add_new();
	$("#userComment").unblock();
	UnblockUI();
	
}

function AfterModifyhWithoutError()
{
	window.location = edp_domain_url + "user_review";
}

function AfterPublishWithError( errMsg )
{
	MessageBox( errMsg, "消息框", { yes: function(){
		$("#userComment").unblock();
		UnblockUI();
	}}, true );
}

var score = -1;
var service = -1;
var reality = -1;
var velocity = -1;
var rate = -1;
var rateGrades = ['差', '一般', '好', '很好', '非常好'];
function MouseOutEvent()
{
	/*
	if( $("#action").val() == "modify_review" ){
		//global object map
		var ObjectMap = {
			'serviceblock' : $("#service").val(),
			'realityblock' : $("#reality").val(),
			'velocityblock' : $("#velocity").val(),
			'rateblock' : $("#rate").val(),
			'scoreblock' : $("#score").val()
		}

		//restore its value in database
		LoadScore( $(this), eval("ObjectMap." + $(this).attr("id")) );
	}
	*/
	//else{
		var val = $(this).prev().val();
		distance = $(this).attr("distance");
		baseline = $(this).attr("baseline");
		offsety = parseInt(baseline) - (parseInt(val)+1) * parseInt(distance); //update by bo@0720

		$(this).css( 'background', 'transparent url(' + edp_static_domain_url + 'image/rank.gif) no-repeat scroll 0px ' + offsety + 'px' );
	//}
	
	//add by bo @0720
	$('#ratingPopTip').css({"visibility":"hidden"});	
}

function AddProductTipEnterEvent(e){
		
	$('#addProductTip').css({"visibility":"hidden"});
    $('#addProductTip').html("您可以在对店铺发表点评时，选择当时所买的商品，增加点评的可信度。<a target='_blank' href='http://www.huakaili.com/help/?subpage=201#3'>了解详情</a>");	
	$('#addProductTip').css({"top":(e.pageY+10)+"px","left":(e.pageX)+"px","visibility":""});	
}
function AddProductTipOutEvent(){
		
		window.setTimeout(function()
		{   
 			$('#addProductTip').css({"visibility":"hidden"}); 
		}, 5000);   
		
   
}


function MouseEnterEvent(e)
{
	distance = $(this).parent().attr("distance");
	baseline = $(this).parent().attr("baseline");
	height = $(this).attr("value");
	height = parseInt(baseline) - (parseInt(height)+1) * parseInt(distance);  //bo update +1@0720
	$(this).parent().css( 'background', 'transparent url(' + edp_static_domain_url + 'image/rank.gif) no-repeat scroll 0px ' + height + 'px' );


	//add by bo @0720
    $('#ratingPopTip').html("<span><em>"+parseInt($(this).attr("value"))+"</em>分 "+rateGrades[$(this).attr("value")]+"</span><strong></strong>");	
	$('#ratingPopTip').css({"top":(e.pageY+10)+"px","left":(e.pageX)+"px","visibility":""});	
}

function SetCheckBoxList( id, selectValues ){
	//	alert( selectValues );
	var idArray = selectValues.split(',');
	for(i in idArray){
		$( '#'+id+idArray[i] ).attr('checked', true);
	}
}

function LoadScore( element, oldscore )
{
	distance = element.attr("distance");
	baseline = element.attr("baseline");
	height = parseInt(baseline) - parseInt(oldscore) * parseInt(distance);
	element.css( 'background', 'transparent url(' + edp_static_domain_url + 'image/rank.gif) no-repeat scroll 0px ' + height + 'px' );
}

function SelectScoreEvent()
{
	cate = $(this).parent().attr("cate");
	selectedValue = parseInt($(this).attr("value")) + 1;
	eval( cate + " = selectedValue" );
	$( "#" + cate ).val( selectedValue - 1 );
	
	//add by bo @0720
	$(this).parent().siblings().filter('#ratingResult').html("<span><em>"+parseInt($(this).attr("value"))+"</em>分 — "+rateGrades[$(this).attr("value")]+"</span>");
}

function send_product_request()
{
	  var params = $('#search_product_form').serialize();
      $.ajax(
    	{
                type: 'post',
                url: edp_domain_url + '/ajax_product_in_shop/?tiny=2',
                data: params,
                timeout: 5000,
				global:false,
	            beforeSend: function()
	            {
    	  			$("#result").text("正在获取商品列表!");
				 
				},
				error: function(XMLHttpRequest, textStatus, errorThrown)
				{
					$("#result").text( "错误，请稍后再试..." );
				},
                success: function( data, textStatus )
                {
					$("#result").html( data );
					setup_link_after_load();
                }
         });
      
	
}

function setup_link_after_load()
{
	$("#addproduct .pagebox a").each(
			function()
			{
				if( $(this).attr('href') )
				{
					$(this).bind("click", function(event){
						event.preventDefault();
						search_list_page( $(this).attr('href') );
					});
							
				}
			}
	);
	
	$("#addproduct .pagebox").css( 'width', '400px');
	
	$("#addproduct .pagecode").css( 'float', 'left');
	$("#addproduct .pagebox a").css( "cursor", "pointer" );
	
	
}

function search_list_page( addr )
{
     $.ajax(
   	 {
   		 type: 'get',
         url: addr,
		 timeout: 5000,
		 global:false,
	     beforeSend: function()
	     {
   		 	$("#result").text("正在搜索...!");
		 },
		 error: function()
		 {
			$("#result").text("发生错误，稍后再试...");
		 },
         success: function( data, textStatus )
         {
			$("#result").html( data );
			setup_link_after_load();
         }
     });
}

// add new upload file field
function add_new()
{ 
	
	//var content_added = "<div id=\"fileblock\" class=\"fileblock\"><input class=\"input_1\" type=\"text\" readonly=\"readonly\" id=\"picpath\" /> <div style=\"padding-top:5px;color: white; font-size: 12px; background: transparent url(static/image/btn.gif) no-repeat scroll right center; overflow: hidden; width: 83px; height: 22px; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous; display: inline; position: absolute;\">&nbsp; &nbsp; &nbsp;浏览</div><input class=\"file_1\" type=\"file\" name=\"files[]\"	id=\"files\" onchange=\"set_file_name(this);\" style=\"position: relative; height: 22px; width: 83px; display: inline; cursor: pointer;   opacity:0; filter:alpha(opacity=0);  z-index:10\" /> <span style=\"margin-left: 2px;\">保存名字:</span> <input type=\"text\" name=\"picnames[]\" id=\"picnames\" /> <a onclick=\"del_file(this);\">删除</a></div>";


	var content_added = "<div id=\"fileblock\" class=\"fileblock\"><input class=\"input_1\" type=\"hidden\" readonly=\"readonly\" id=\"picpath\" /> <input class=\"file_1\" type=\"file\" name=\"files[]\"	id=\"files\" onchange=\"set_file_name(this);\"  contenteditable=\"false\" size=\"30\"/> <span style=\"margin-left: 5px;\">保存名字：</span> <input type=\"text\" name=\"picnames[]\" id=\"picnames\" class=\"pic_name\" /> <a onclick=\"del_file(this);\">删除</a></div>";

	if( $(".fileblock").length == 0 )
		$("#uploadlocator:last").after( content_added );  
	else
		$(".fileblock:last").after( content_added );
}


// delete upload file field
function del_file( this_ )
{
	$(this_).parent().remove();
}
	
// open the product search dialog
function add_product()
{
	$.blockUI(
		{
		     message: $("#addproduct"),    
		 	 css: 
		 	 { 
		        padding:        0,
		        margin:         0,
		        top:            '10%', 
				left:           '35%', 
		        width:          '600',
		        textAlign:      '', 
		        color:          '', 
		        border:         '',
		        backgroundColor:'',       				
		        cursor:         'wait'				        
			  }
		 }
	 ); 		
	
	
	$('#search_product_form').submit(
			function()
			{
					send_product_request();
					return false;
			}
	);
	
	$( '#closeWindow').click(
			function()
			{
				$.unblockUI();
			}
	);
	$( '#close').click(
			function()
			{
				$.unblockUI();
			}
	);
}





// add the selected product to the product list
function add_to_productlist( id_, this_)
{
	var product_list = $("#product_lists").val();
	if( product_list.indexOf(id_ + ",") == -1 )
	{
		product_list = product_list + id_ + "," ;
	
		$("#product_list").html( $("#product_list").html() + 
				"<div><a href=\"#\">" + $(this_).prev().text() + "</a>&nbsp;&nbsp;&nbsp;<a onclick=\"remove_from_productlist(" + 
				 id_ +  ", this)\">删除</a></div>" );
		
		$("#product_lists").val( product_list );
	}
	
	var nextele = $(this_);
	nextele.prev().remove();
	nextele.next().remove();
	nextele.remove();
}


//remove the product from the product list
function remove_from_productlist( id_, this_ )
{
	var pattern = id_ + "," ;
	var product_list = $("#product_lists").val();
	product_list = product_list.replace( pattern, "");
	$("#product_lists").val( product_list );
	$(this_).parent().remove();
}


// filter the file name uploaded
function set_file_name( this_ )
{
	
	var file = $(this_).val();
	var fileReg = /\.(jpg|gif|bmp|png|jpeg)$/i;
	if( !fileReg.test(file) )
	{
		alert( "只允许上传 jpg/gif/bmp/png/jpeg 格式的图片文件！" );
		$(this_).val("");
		return;
	}
	
	file = file.substring( file.lastIndexOf("\\") + 1 );
	
	$(this_).parent().children().filter("#picnames").val( file  );
	$(this_).parent().children().filter("#picpath").val( $(this_).val() );
	
}




// add the tag to the tag text
function set_tag( this_ )
{
	var tags = $("#tag").val();
	
	if( tags.indexOf( $(this_).text() + " " ) == -1 )
	{
		if( tags != "" && tags.charAt( tags.length - 1 ) != ' ' )
			tags += " ";
		
		tags += $(this_).text() + " ";
		$("#tag").val( tags );
		$(this_).css( "background", "red" );
	}
	else
	{
		tags = tags.replace( $(this_).text() + " ", "" );
		$("#tag").val( tags );
		$(this_).css( "background", "" );
	}
}


// check all the input field in the form before submit
function check_validation()
{
	if( Login( GetFormSubmitEvent($("#add_review_form")[0]) )== false )
		return false;
	//var has_error = 0;
	
	if( $("#content").val().trim() == "" || $("#content").val().length<50)
	{
		alert( "评论内容不能小于50个字符，请认真发表点评。" );
		return false;
	}
	
	var pic_names = $("input:text[name='picnames[]']");
	var pic_path = $("input:file[name='files[]']");
	var pic_count = pic_path.size();
			
	for( i = 0; i < pic_count; i++ )
	{
		if( pic_path[i].value.trim() != "" && pic_names[i].value.trim() == "" )
		{
			alert( "文件名称不能为空!" );
			$(pic_names[i]).css("background", "red");
			//has_error = 1;
			return false;
			
		}
	}
	
	if( $("#vcode").val().length > 4 || $("#vcode").val().length == 0 )
    {
        alert("请填写正确的验证码！");
        return false;
    }
	
}

function del_pic( this_ )
{
	$(this_).parent().remove();
}
